package web.servlet.response;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Author Administrator
 * @Date 2020/5/22 10:01
 **/
@WebServlet("/downLoad")
public class DownLoad extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String filename = req.getParameter("filename");
        /*获取真实路径*/
        String realPath = req.getServletContext().getRealPath("/img/" + filename);
        /*输入输出*/
        ServletOutputStream ops = resp.getOutputStream();
        FileInputStream fis=new FileInputStream(realPath);
        /*中文文件名*/
        String agent = req.getHeader("User-Agent");
        filename = DownLoadUtils.getFileName(agent, filename);
        System.out.println(filename);
        resp.setHeader("Content-Disposition","attachment;filename="+filename);
        byte[] bytes=new byte[1024];
        int len=0;
        while((len=fis.read(bytes))!=-1){
            ops.write(bytes,0,len);
        }
        ops.close();
        fis.close();
    }
}
